import { LoginService } from '@service/login.service';
import { AbsFormUtil } from '@abstract/form';
import { AfterViewInit, Component, OnInit } from '@angular/core';
import { ExampleFlatNode, ISystemOrganize, ISystemUser } from '@model/system';
import { NzTreeFlatDataSource, NzTreeFlattener } from 'ng-zorro-antd/tree-view';
import { SelectionModel } from '@angular/cdk/collections';
import { FlatTreeControl } from '@angular/cdk/tree';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal';
import { SystemUserEditComponent } from './system-user-edit/system-user-edit.component';
import { SystemService } from '@service/system.service';
import { TreeService } from '@service/tree.service';
import { AuthService } from '@service/auth.service';


@Component({
	selector: 'app-user',
	templateUrl: './system-user.component.html',
	styleUrls: ['./system-user.component.less']
})
export class SystemUserComponent extends AbsFormUtil implements OnInit, AfterViewInit {
	isCardLoading = false;
	nzLoading = false;
	isReload = false;
	data = [];
	selectNode = null;
	constructor(
		private systemService: SystemService,
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private nzModalService: NzModalService,
		private treeService: TreeService,
		private loginService: LoginService,
		private authService: AuthService

	) {
		super();
		this.authList = this.authService.getAuth();
	}


	ngOnInit() {
		this.buildForm();
		this.onSearch();
		this.getDepartList();
	
	
		this.selectListSelection.changed.subscribe(selectList => {
			this.selectNode = selectList.added[0] || null;
			// console.log(this.selectNode);
			this.onSearch(true);
		});
	}
	reload() {
		this.isReload = true;
		this.getDepartList();
		this.selectNode = null;
		this.onSearch(true);
		setTimeout(() => {
			this.isReload = false;
		}, 1000);
	}

	private async getDepartList() {
		this.isCardLoading = true;
		const res = await this.systemService.getDepartList();
		const treeData = this.treeService.convertListToTree(res.dept || [], 0);
		this.dataSource.setData(treeData);
		setTimeout(() => {
			this.isCardLoading = false;
		}, 1000);
	}


	private transformer = (node: ISystemOrganize, level: number) => {
		return {
			expandable: !!node.children && node.children.length > 0,
			name: node.deptName,
			level: level,
			id: node.id
		};
	};
	selectListSelection = new SelectionModel<ExampleFlatNode>();

	treeControl = new FlatTreeControl<ExampleFlatNode>(
		node => node.level,
		node => node.expandable
	);

	treeFlattener = new NzTreeFlattener(
		this.transformer,
		node => node.level,
		node => node.expandable,
		node => node.children
	);

	dataSource = new NzTreeFlatDataSource(this.treeControl, this.treeFlattener);



	hasChild = (_: number, node: ExampleFlatNode) => node.expandable;

	ngAfterViewInit(): void {
		// setTimeout(() => {
		// 	this.treeControl.expand(this.getNode('Vegetables')!);
		// }, 300);
	}

	getNode(name: string): ExampleFlatNode | null {
		return this.treeControl.dataNodes.find(n => n.name === name) || null;
	}







	
	buildForm() {
		this.validateForm = this.fb.group({
			userName: [''],
		});
	}

	async onSearch(isPageInit?: boolean) {
		this.nzLoading = true;
		if (isPageInit) {
			this.page.page = 1;
		}
		const formValue = this.validateForm.value;
		formValue.deptId = this.selectNode ? this.selectNode.id : ''
		const params = { ...formValue, ...this.page };
		const result = await this.systemService.getUserList(params);
		this.data = result.page.list;
		this.page.total = result.page.totalCount;
		this.nzLoading = false;
	}


	pageChange(isPageInit?: boolean) {
		if (isPageInit) {
			this.page.page = 1;
		}
		this.onSearch();
	}
	async del(item) {
		await this.systemService.deleteUser(item.id);
		this.nzMessageService.success('删除成功');
		this.onSearch(true);
	}

	resetPwd(item) {
		this.nzModalService.confirm({
			nzTitle: `真的要将${item.userName}重置密码吗？`,
			nzContent: '',
			nzOnOk: async () => {
				await this.loginService.resetPassword(item.id);
				this.nzMessageService.success('重置密码成功,密码为123456');
			}
		});
	}

	addUser(item?: ISystemUser) {
		if (!this.selectNode && !item) {
			this.nzMessageService.info('请先选择部门!');
			return;
		}
		const _this = this;
		this.nzModalService.create({
			nzTitle: item ? '编辑用户' : '新增用户',
			nzContent: SystemUserEditComponent,
			nzWidth: '70%',
			nzComponentParams: {
				id: item?.id
			},
			nzFooter: [
				{
					label: '确定',
					type: 'primary',
					loading: false,
					onClick:(componentInstance) => {
						(async () =>{
							const resForm = componentInstance.onSubmit();
							if (resForm) {
								const id = componentInstance.id || ''
								resForm.roleList = resForm.roleList.filter(it => it.checked).map(itm => itm.value);
								resForm.deptId = this.selectNode?.id;
								resForm.id = id;
								const result = await this.systemService.saveUser(resForm);
								if (result.status !== 0) {
									this.nzMessageService.error(result.msg || '保存失败');
									return;
								}
								componentInstance.destroyModal();
								id ? this.onSearch() : Object.assign(item, resForm);
								this.nzMessageService.success('保存成功');
							}
						})();
					}
				},
				{
					label: '取消',
					onClick: componentInstance => {
						componentInstance.destroyModal();
					}
				}
			]
		})
	}

}
